package cn.deschen.mp.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

/**
 * @Author hanbin_chen
 * @Description mybatis-plus代码生成
 * @DateTime 2021/6/1
 * @Version V1.0.0
 */
@Slf4j
public class CodeGenerate {


    public static String outPuDir;

    public static String formatServiceName;

    public static String dbUrl;

    public static String dbUsername;

    public static String dbPassword;

    public static String mpParentDir;

    public static String entityDir;

    public static String mapperDir;

    public static String serviceDir;

    public static String serviceImplDir;

    public static String mapperXmlDir;

    public static String superEntityClass;

    public static String[] superEntityColumns;

    static {
        String propertiesUrl = System.getProperty("user.dir") + "/mybatis-plus-generator/src/main/resources/generator.properties";
        Properties pros = loadProps(propertiesUrl);
        outPuDir = System.getProperty("user.dir") + pros.getProperty("outPuDir");
        formatServiceName = pros.getProperty("formatServiceName");
        dbUrl = pros.getProperty("dbUrl");
        dbUsername = pros.getProperty("dbUsername");
        dbPassword = pros.getProperty("dbPassword");
        mpParentDir = pros.getProperty("mpParentDir");
        entityDir = pros.getProperty("entityDir");
        mapperDir = pros.getProperty("mapperDir");
        serviceDir = pros.getProperty("serviceDir");
        serviceImplDir = pros.getProperty("serviceImplDir");
        mapperXmlDir = System.getProperty("user.dir") + pros.getProperty("mapperXmlDir");
        superEntityClass = pros.getProperty("superEntityClass");
        superEntityColumns = pros.getProperty("superEntityColumns").trim().split(",");
    }

    /**
     * 运行这个main方法进行代码生成
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(outPuDir);
        gc.setAuthor("deschen");
        gc.setOpen(false);
        // 实体属性 Swagger2 注解
        gc.setSwagger2(true);
        gc.setServiceName(formatServiceName);
        gc.setDateType(DateType.TIME_PACK);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dbUrl);
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(dbUsername);
        dsc.setPassword(dbPassword);
        // 转换类型
        // dsc.setTypeConvert(new MySqlTypeConvertCustom());
        mpg.setDataSource(dsc);

        /*
        包配置，可以根据自己的项目情况自定义生成后的存放路径
        entity默认路径为父目录.entity
        mapper默认路径为父目录.mapper
        service默认路径为父目录.service
        serviceImpl默认路径为父目录.service.impl
        controller默认路径为父目录.controller
        */
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        //设置父目录
        pc.setParent(mpParentDir);
        //自定义entity的生成位置
        pc.setEntity(entityDir);
        // 自定义mapper的生成位置
        pc.setMapper(mapperDir);
        // 自定义service的生成位置
        pc.setService(serviceDir);
        // 自定义serviceImpl的生成位置
        pc.setServiceImpl(serviceImplDir);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return mapperXmlDir + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        templateConfig.disable(TemplateType.CONTROLLER);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setSuperEntityClass(superEntityClass);
        strategy.setSuperEntityColumns(superEntityColumns);
        // 设置表前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 读取控制台内容
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 读取外部配置文件
     * @param propertiesUrl
     */
    public static Properties loadProps(String propertiesUrl) {
        Properties props = new Properties();
        try(InputStream in = new BufferedInputStream(new FileInputStream(propertiesUrl))) {
            props.load(in);
        } catch (FileNotFoundException e) {
            log.error("jdbc.properties文件未找到");
            throw new RuntimeException(e.getMessage());
        } catch (IOException e) {
            log.error("出现IOException");
            throw new RuntimeException(e.getMessage());
        }
        log.debug("properties文件内容：" + props);
        return props;
    }
}

/**
 * 自定义类型转换
 */
class MySqlTypeConvertCustom extends MySqlTypeConvert implements ITypeConvert {

    @Override
    public IColumnType processTypeConvert(GlobalConfig config, String fieldType) {
        String t = fieldType.toLowerCase();
        if (t.contains("tinyint(1)")) {
            return DbColumnType.INTEGER;
        }
        return super.processTypeConvert(config, fieldType);
    }
}
